﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CloseDisplay1
{
    /// <summary>
    /// 系统锁屏/解锁监听工具类
    /// </summary>
    public class LockScreenWatcher : IDisposable
    {
        /// <summary>
        /// 当前系统锁屏状态，true = 锁屏，false = 解锁
        /// 默认未锁屏
        /// </summary>
        public bool IsLocked { get; set; } = false;

        /// <summary>
        /// 锁屏事件
        /// </summary>
        public event Action OnLock;

        /// <summary>
        /// 解锁事件
        /// </summary>
        public event Action OnUnlock;

        /// <summary>
        /// 构造函数，自动订阅系统事件
        /// </summary>
        public LockScreenWatcher()
        {
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
        }

        private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            switch (e.Reason)
            {
                case SessionSwitchReason.SessionLock:
                    IsLocked = true;
                    OnLock?.Invoke();
                    break;
                case SessionSwitchReason.SessionUnlock:
                    IsLocked = false;
                    OnUnlock?.Invoke();
                    break;
            }
        }

        /// <summary>
        /// 释放资源，取消事件订阅
        /// </summary>
        public void Dispose()
        {
            SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
        }
    }
}
